package com.naiterui.ehp.bp.support.bean.ser;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.naiterui.ehp.bp.support.bean.annotation.Fen2Yuan;

/**
 * <pre>
 *   字典过滤
 * </pre>
 *
 * @author 王泽浩
 * @date 2019-02-19 14:14
 * @since 1.0.0
 */
public class Fen2YuanFieldSerializer extends StdSerializer<Integer> implements ContextualSerializer {

    private static final long serialVersionUID = -6171864107747220506L;

    private final String pattern;

    @SuppressWarnings("unused")
    public Fen2YuanFieldSerializer() {
        super(Integer.class);
        this.pattern = "###,##0.00";
    }


    private Fen2YuanFieldSerializer(JavaType type, String pattern) {
        super(type);
        this.pattern = pattern;
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        Fen2Yuan fen2Yuan = property.getAnnotation(Fen2Yuan.class);
        if (fen2Yuan != null) {
            return new Fen2YuanFieldSerializer(property.getType(), fen2Yuan.pattern());
        }
        return null;
    }

    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        BigDecimal fen = BigDecimal.valueOf(value);
        gen.writeObject(new DecimalFormat(this.pattern).format(fen.divide(BigDecimal.valueOf(100))));
    }
}
